<template>
  <el-dialog v-model="visible" title="订单参与人列表" width="80%" :before-close="handleClose">
    <!-- 搜索栏 -->
    <div class="handle-box">
      <el-input v-model="searchForm.id" placeholder="ID" class="handle-input mr10" clearable />
      <!-- <el-input v-model="searchForm.userId" placeholder="用户ID" class="handle-input mr10" clearable /> -->
      <el-input v-model="searchForm.participantsName" placeholder="姓名" class="handle-input mr10" clearable />
      <el-input v-model="searchForm.participantsIdCard" placeholder="证件号" class="handle-input mr10" clearable />
      <el-input v-model="searchForm.participantsMobile" placeholder="手机号" class="handle-input mr10" clearable />
      <!-- <el-select v-model="searchForm.votesStatus" placeholder="状态" class="handle-select mr10" clearable style="width:300px">
        <el-option label="全部" value="" />
        <el-option label="待核销" :value="0" />
        <el-option label="已核销" :value="1" />
        <el-option label="已取消" :value="2" />
        <el-option label="已过期" :value="3" />
      </el-select> -->
      <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
      <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
    </div>

    <!-- 表格 -->
    <el-table :data="tableData" border class="table" ref="tableRef" header-cell-class-name="table-header" row-key="id">
      <el-table-column prop="id" label="ID" />
      <!-- <el-table-column prop="userId" label="用户ID">
        <template #default="scope">
          {{ scope.row.userId || '-' }}
        </template>
</el-table-column> -->
      <el-table-column prop="participantsName" label="姓名" />
      <el-table-column prop="participantsIdCard" label="证件号">
        <template #default="scope">
          {{ scope.row.participantsIdCard || '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="participantsMobile" label="手机号">
        <template #default="scope">
          {{ scope.row.participantsMobile || '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="votesStatus" label="状态">
        <template #default="scope">
          <el-tag v-if="scope.row.votesStatus !== undefined && scope.row.votesStatus !== null" :type="statusTagType(scope.row.votesStatus)">
            {{ statusText(scope.row.votesStatus) }}
          </el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="160" align="center">
        <template #default="scope">
          <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="text" style="color:#f56c6c;" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pagination.currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="pagination.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="pagination.total" />
    </div>

    <!-- 新增/编辑弹窗 -->
    <el-dialog v-model="editDialog.visible" :title="editDialog.isEdit ? '编辑参与人' : '新增参与人'" width="400px" @close="resetEditDialog">
      <el-form :model="editDialog.form" :rules="editDialog.rules" ref="editFormRef" label-width="80px">
        <el-form-item label="姓名" prop="participantsName">
          <el-input v-model="editDialog.form.participantsName" />
        </el-form-item>
        <el-form-item label="证件号" prop="participantsIdCard">
          <el-input v-model="editDialog.form.participantsIdCard" />
        </el-form-item>
        <el-form-item label="手机号" prop="participantsMobile">
          <el-input v-model="editDialog.form.participantsMobile" />
        </el-form-item>
        <!-- <el-form-item label="状态" prop="votesStatus">
          <el-select v-model="editDialog.form.votesStatus" placeholder="请选择">
            <el-option label="待核销" :value="0" />
            <el-option label="已核销" :value="1" />
            <el-option label="已取消" :value="2" />
            <el-option label="已过期" :value="3" />
          </el-select>
        </el-form-item> -->
      </el-form>
      <template #footer>
        <el-button @click="editDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="submitEdit">确定</el-button>
      </template>
    </el-dialog>

    <!-- <template #footer>
      <div class="dialog-footer">
        <div>
          <el-button @click="handleClose">关闭</el-button>
        </div>
      </div>
    </template> -->
  </el-dialog>
</template>

<script>

import { getActivityOrderVotes, addActivityOrderVotes, updateActivityOrderVotes, deleteActivityOrderVotes, getActivityOrderVotesByOrder } from "@/api/content";

export default {
  name: "OrderParticipantDialog",
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    orderId: {
      type: [String, Number],
      required: true
    },
    orderTradeId: {
      type: [String, Number],
      required: true
    },
    votesGoods: {
      type: [String, Number],
      required: true
    }
  },
  emits: ['update:modelValue'],
  data() {
    return {
      searchForm: {
        id: '',
        userId: '',
        participantsName: '',
        participantsIdCard: '',
        participantsMobile: '',
        votesStatus: ''
      },
      tableData: [],
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      editDialog: {
        visible: false,
        isEdit: false,
        form: {
          id: '',
          participantsName: '',
          participantsIdCard: '',
          participantsMobile: '',
          votesStatus: 0
        },
        rules: {
          participantsName: [
            { required: true, message: '请输入姓名', trigger: 'blur' }
          ],
          participantsIdCard: [
            { required: true, message: '请输入证件号', trigger: 'blur' },
            {
              validator: (rule, value, callback) => {
                if (!value) return callback();
                // 简单身份证校验（支持15/18位，18位可带X/x）
                const reg = /^(\d{15}|\d{17}[\dXx])$/;
                if (!reg.test(value)) {
                  callback('请输入正确的身份证号');
                } else {
                  callback();
                }
              }, trigger: 'blur'
            }
          ],
          participantsMobile: [
            { required: true, message: '请输入手机号', trigger: 'blur' },
            { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
          ],
          votesStatus: [
            { required: true, message: '请选择状态', trigger: 'change' }
          ]
        }
      }
    };
  },
  computed: {
    visible: {
      get() {
        return this.modelValue;
      },
      set(val) {
        this.$emit('update:modelValue', val);
      }
    }
  },
  watch: {
    visible(newVal) {
      if (newVal) {
        this.getData();
      }
    }
  },
  methods: {
    statusText(status) {
      switch (status) {
        case 0: return '待核销';
        case 1: return '已核销';
        case 2: return '已取消';
        case 3: return '已过期';
        default: return '-';
      }
    },
    statusTagType(status) {
      switch (status) {
        case 0: return 'info';
        case 1: return 'success';
        case 2: return 'danger';
        case 3: return 'warning';
        default: return '';
      }
    },
    handleSearch() {
      this.pagination.currentPage = 1;
      this.getData();
    },
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.pagination.currentPage = 1;
      this.getData();
    },
    handleCurrentChange(val) {
      this.pagination.currentPage = val;
      this.getData();
    },
    buildSearchParams() {
      const params = {
        limit: this.pagination.pageSize,
        offset: this.pagination.currentPage,
        orderId: this.orderId,
        orderTradeId: this.orderTradeId,
        votesGoods: this.votesGoods
      };
      Object.keys(this.searchForm).forEach(key => {
        if (this.searchForm[key] !== '' && this.searchForm[key] !== null && this.searchForm[key] !== undefined) {
          params[key] = this.searchForm[key];
        }
      });
      return params;
    },
    async getData() {
      try {
        let params = this.buildSearchParams();
        params.id = this.orderId
        const response = await getActivityOrderVotesByOrder(params);
        if (response && response.data) {
          this.tableData = response.data.rows || response.data;
          if (response.data.total !== undefined) {
            this.pagination.total = response.data.total;
          }
        }
      } catch (error) {
        this.$message.error('获取参与人数据失败');
      }
    },
    handleAdd() {
      this.editDialog.isEdit = false;
      this.editDialog.form = {
        id: '',
        participantsName: '',
        participantsIdCard: '',
        participantsMobile: '',
        votesStatus: 0
      };
      this.editDialog.visible = true;
    },
    handleEdit(row) {
      this.editDialog.isEdit = true;
      this.editDialog.form = { ...row };
      this.editDialog.visible = true;
    },
    async handleDelete(row) {
      this.$confirm('确定要删除该参与人吗？', '提示', { type: 'warning' })
        .then(async () => {
          await deleteActivityOrderVotes({ id: row.id });
          this.$message.success('删除成功');
          this.getData();
        })
        .catch(() => { });
    },
    async submitEdit() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return;
        const form = this.editDialog.form;
        const params = {
          ...form,
          orderId: this.orderId,
          orderTradeId: this.orderTradeId,
          votesGoods: this.votesGoods
        };
        try {
          if (this.editDialog.isEdit) {
            await updateActivityOrderVotes(params);
            this.$message.success('编辑成功');
          } else {
            await addActivityOrderVotes(params);
            this.$message.success('新增成功');
          }
          this.editDialog.visible = false;
          this.getData();
        } catch (e) {
          this.$message.error('操作失败');
        }
      });
    },
    resetEditDialog() {
      this.editDialog.form = {
        id: '',
        participantsName: '',
        participantsIdCard: '',
        participantsMobile: '',
        votesStatus: 0
      };
    },
    handleClose() {
      this.visible = false;
    }
  },
};
</script>

<style lang='scss' scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 200px;
  display: inline-block;
}

.table {
  width: 100%;
  font-size: 14px;
}

.mr10 {
  margin-right: 10px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.selected-info {
  color: #606266;
  font-size: 14px;
}

// 状态标签样式
.el-tag {
  border-radius: 4px;
}

// 操作按钮样式
.el-button--mini {
  padding: 5px 8px;
  font-size: 12px;
  border-radius: 3px;
}

// 表格样式调整
::v-deep .table-header {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 500;
}

::v-deep .el-table {
  border: 1px solid #ebeef5;

  .el-table__header-wrapper {
    .el-table__header {
      th {
        background-color: #f5f7fa;
        border-color: #ebeef5;
      }
    }
  }

  .el-table__body-wrapper {
    .el-table__body {
      td {
        border-color: #ebeef5;
      }
    }
  }
}

// 输入框和选择器样式
::v-deep .el-input {
  .el-input__inner {
    border-radius: 4px;
    border-color: #dcdfe6;

    &:focus {
      border-color: #409eff;
    }
  }
}

::v-deep .el-select {
  .el-input__inner {
    border-radius: 4px;
    border-color: #dcdfe6;
  }
}

// 分页样式
::v-deep .el-pagination {
  .el-pagination__sizes {
    .el-select .el-input {
      width: 100px;
    }
  }

  .btn-next,
  .btn-prev {
    border-radius: 4px;
  }

  .el-pager li {
    border-radius: 4px;
    margin: 0 2px;
  }
}

// 弹窗表单样式
::v-deep .el-dialog {
  border-radius: 8px;

  .el-dialog__header {
    border-bottom: 1px solid #ebeef5;
    padding: 20px 20px 15px;

    .el-dialog__title {
      font-weight: 500;
      color: #303133;
    }
  }

  .el-dialog__body {
    padding: 20px;
  }

  .el-dialog__footer {
    border-top: 1px solid #ebeef5;
    padding: 15px 20px 20px;
  }
}

::v-deep .el-form {
  .el-form-item {
    margin-bottom: 18px;

    .el-form-item__label {
      color: #606266;
      font-weight: 500;
    }

    .el-form-item__content {

      .el-input,
      .el-select {
        width: 100%;
      }
    }
  }
}

// 按钮样式
::v-deep .el-button {
  border-radius: 4px;
  font-weight: 400;

  &.el-button--primary {
    background-color: #409eff;
    border-color: #409eff;

    &:hover {
      background-color: #66b1ff;
      border-color: #66b1ff;
    }
  }

  &.el-button--danger {
    &:hover {
      background-color: #f78989;
      border-color: #f78989;
    }
  }
}
</style>